package bookmanagementsystem.dao;

import bookmanagementsystem.model.Admin;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AdminDAO {
    private static final String URL = "jdbc:mysql://localhost:3306/book_management_system";
    private static final String USERNAME = "root";
    static final String PASSWORD = "root";

    // 注册管理员方法
    public boolean registerAdmin(Admin admin) {
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO admin_table (admin_id, password) VALUES (?,?)")) {

            preparedStatement.setString(1, admin.getAdminID());
            preparedStatement.setString(2, admin.getPassword());

            int rowsAffected = preparedStatement.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            // 更详细地处理数据库插入错误
            e.printStackTrace();
            return false;
        }
    }

    // 管理员登录验证方法
    public boolean loginAdmin(String adminID, String password) {
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM admin_table WHERE admin_id =? AND password =?")) {

            preparedStatement.setString(1, adminID);
            preparedStatement.setString(2, password);

            ResultSet resultSet = preparedStatement.executeQuery();
            return resultSet.next();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 修改管理员密码方法
    public boolean updateAdminPassword(String adminID, String newPassword) {
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement("UPDATE admin_table SET password =? WHERE admin_id =?")) {

            preparedStatement.setString(1, newPassword);
            preparedStatement.setString(2, adminID);

            int rowsAffected = preparedStatement.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }


}